package com.dctp.ems.interceptor;

import static com.dctp.common.vo.TipCode.NOT_LOGIN;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import com.dctp.common.vo.JsonResult;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

public class AuthInterceptor implements Interceptor {


    // 白名单路径（根据实际补充）
    private static final String[] WHITE_LIST = {
        "/ems/admin/login",
    };

    @Override
    public void intercept(Invocation inv) {
        String path = inv.getActionKey(); // Controller 的路由 key，如 /ems/admin/login
        HttpServletRequest request = inv.getController().getRequest();

        // 白名单放行
        for (String white : WHITE_LIST) {
            if (path.equals(white) || path.startsWith(white + "/")) {
                inv.invoke();
                return;
            }
        }

        String token = null;
        // 1. header: token 或 authorization: Bearer xxx
        token = request.getHeader("token");
        if (StrKit.isBlank(token)) {
            String auth = request.getHeader("authorization");
            if (StrKit.notBlank(auth) && auth.toLowerCase().startsWith("bearer ")) {
                token = auth.substring(7).trim();
            }
        }

        // 2. cookie: authorized-token
        if (StrKit.isBlank(token) && request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                if ("authorized-token".equals(cookie.getName())) {
                    try {
                        String val = java.net.URLDecoder.decode(cookie.getValue(), "UTF-8");
                        // 简单解析 accessToken
                        int start = val.indexOf("\"accessToken\":");
                        if (start >= 0) {
                            int quoteStart = val.indexOf("\"", start + 14);
                            int quoteEnd = val.indexOf("\"", quoteStart + 1);
                            if (quoteStart >= 0 && quoteEnd > quoteStart) {
                                token = val.substring(quoteStart + 1, quoteEnd);
                            }
                        }
                    } catch (Exception ignore) {}
                }
            }
        }

        if (StrKit.isBlank(token)) {
            inv.getController().renderJson(JsonResult.fail(NOT_LOGIN));
            return;
        }

        // 查库，token合法才放行
        Record admin = Db.findFirst("select * from card_enterprise_admin where token=?", token);
        if (admin == null) {
            inv.getController().renderJson(JsonResult.fail(NOT_LOGIN));
            return;
        }
        // 注入 admin 供后续 Controller 使用
        inv.getController().setAttr("reqUser", admin);
        inv.invoke();
    }

}
